package cn.wolfcode.business.service.impl;

import cn.wolfcode.business.domain.BusBpmnInfo;
import cn.wolfcode.business.domain.BusServiceItem;
import cn.wolfcode.business.domain.CarPackageAudit;
import cn.wolfcode.business.mapper.BusServiceItemMapper;
import cn.wolfcode.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.business.service.IBusBpmnInfoService;
import cn.wolfcode.business.service.IBusServiceItemService;
import cn.wolfcode.common.core.domain.entity.SysUser;
import cn.wolfcode.common.utils.DateUtils;
import cn.wolfcode.common.utils.SecurityUtils;
import cn.wolfcode.system.service.ISysUserService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务项Service业务层处理
 *
 * @author wolfcode
 * @date 2025-04-26
 */
@Service
@Transactional
public class BusServiceItemServiceImpl implements IBusServiceItemService
{
    @Autowired
    private BusServiceItemMapper busServiceItemMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IBusBpmnInfoService busBpmnInfoService;

    /**
     * 查询服务项
     *
     * @param id 服务项主键
     * @return 服务项
     */
    @Override
    public BusServiceItem selectBusServiceItemById(Long id)
    {
        return busServiceItemMapper.selectBusServiceItemById(id);
    }

    /**
     * 查询服务项列表
     *
     * @param busServiceItem 服务项
     * @return 服务项
     */
    @Override
    public List<BusServiceItem> selectBusServiceItemList(BusServiceItem busServiceItem)
    {
        return busServiceItemMapper.selectBusServiceItemList(busServiceItem);
    }

    /**
     * 新增服务项
     *
     * @param busServiceItem 服务项
     * @return 结果
     */
    @Override
    public int insertBusServiceItem(BusServiceItem busServiceItem)
    {
        //  	- 参数合理性验证
        if(busServiceItem == null){
            throw new RuntimeException("非法参数");
        }
        //      - 前端需要验证的后端都需要再次验证。
        if(busServiceItem.getName() == null || busServiceItem.getOriginalPrice() == null ||
            busServiceItem.getDiscountPrice() == null || busServiceItem.getCarPackage() == null ||
            busServiceItem.getServiceCatalog() == null){
            throw new RuntimeException("非法参数");
        }
        //      - 金额合理化验证
        // BigDecimal 类型比较需要使用 调用者.compareTo(参数) 方法。
        // 规则 调用者 > 参数  返回正数  调用者 < 参数  返回复数  相等则返回0
        //         - 折扣价格 > 0   - 原价 >= 折扣价
        if(!((busServiceItem.getDiscountPrice().compareTo(new BigDecimal("0")) >= 0) &&
            (busServiceItem.getDiscountPrice().compareTo(busServiceItem.getOriginalPrice()) <= 0))){
            throw new RuntimeException("折扣需要大于等于0，且小于等于原价");
        }
        //      - 根据插入的是否是套餐决定审核状态
        if(BusServiceItem.CARPACKAGE_NO.equals(busServiceItem.getCarPackage())){
            //         - 不是套餐则状态设置为 --> 无需审核
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_NO_REQUIRED);
        } else {
            // - 是套餐则状态设置为  -->  初始化
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        }
        //      - 安全性验证：将上下架状态直接设置为下架！
        busServiceItem.setSaleStatus(BusServiceItem.SALESTATUS_OFF);
        busServiceItem.setCreateTime(DateUtils.getNowDate());
        return busServiceItemMapper.insertBusServiceItem(busServiceItem);
    }

    /**
     * 修改服务项
     *
     * @param busServiceItem 服务项
     * @return 结果
     */
    @Override
    public int updateBusServiceItem(BusServiceItem busServiceItem)
    {
        // - 参数合理性验证
        if(busServiceItem == null){
            throw new RuntimeException("非法参数");
        }
        // - 前端需要验证的后端都需要再次验证。
        if(busServiceItem.getName() == null || busServiceItem.getOriginalPrice() == null ||
                busServiceItem.getDiscountPrice() == null || busServiceItem.getCarPackage() == null ||
                busServiceItem.getServiceCatalog() == null){
            throw new RuntimeException("非法参数");
        }
        // - 金额合理化验证
        if(!((busServiceItem.getDiscountPrice().compareTo(new BigDecimal("0")) >= 0) &&
                (busServiceItem.getDiscountPrice().compareTo(busServiceItem.getOriginalPrice()) <= 0))){
            throw new RuntimeException("折扣需要大于等于0，且小于等于原价");
        }
        // - 是否套餐不能更改（服务项是单品，套餐是多个单品。 无法从 1--> 多  也无法从 多 --> 1）
        BusServiceItem oldObj = this.selectBusServiceItemById(busServiceItem.getId());
        if(oldObj == null){
            throw new RuntimeException("非法参数");
        }
        if(!(busServiceItem.getCarPackage().equals(oldObj.getCarPackage()))){
            throw new RuntimeException("是否套餐不能修改");
        }
        // - 这里开始的判定我们都使用数据库中查询出出来的对象判定
        // 必须是下架状态才可以进行修改。
        if(BusServiceItem.SALESTATUS_ON.equals(oldObj.getSaleStatus())){
            throw new RuntimeException("上架的服务项或套餐无法修改");
        }

        //    - 若是套餐
        if(BusServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage())
            //       - 审核中：不能修改。
            && BusServiceItem.AUDITSTATUS_AUDITING.equals(oldObj.getAuditStatus())){
            throw new RuntimeException("状态为审核中的服务项无法修改");
        }
        if(BusServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage())
        && (BusServiceItem.AUDITSTATUS_APPROVED.equals(oldObj.getAuditStatus()) ||
                BusServiceItem.AUDITSTATUS_REPLY.equals(oldObj.getAuditStatus()))){
            // - 审核通过、审核拒绝：可以修改，但是修改后该状态必须变为初始化。（需要重新发起审核）。
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        }
        //       - 初始化：可以直接修改。  - 不是套餐：可以直接修改
        // - 安全性验证：将上下架状态直接设置为下架！
        busServiceItem.setSaleStatus(BusServiceItem.SALESTATUS_OFF);
        return busServiceItemMapper.updateBusServiceItem(busServiceItem);
    }

    /**
     * 批量删除服务项
     *
     * @param ids 需要删除的服务项主键
     * @return 结果
     */
    @Override
    public int deleteBusServiceItemByIds(Long[] ids)
    {
        // 参数合法性验证
        if(ids == null || ids.length != 1){
            throw new RuntimeException("非法参数");
        }
        // 因为不存在批量删除。所以我们直接拿到数组的[0]就是我们传递的 id
        Long id = ids[0];
        BusServiceItem serviceItem = this.selectBusServiceItemById(id);
        if(serviceItem == null){
            throw new RuntimeException("非法参数");
        }
        //  - 必须是下架状态
        if(BusServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())){
            throw new RuntimeException("上架的商品禁止删除");
        }
        // - 若不是套餐可以直接删除
        // - 若是套餐则审批中不能删除。
        if(BusServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage()) // 是套餐
            && BusServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus())){
            throw new RuntimeException("审核中的商品禁止删除");
        }

        return busServiceItemMapper.deleteBusServiceItemById(id);
    }

    /**
     * 删除服务项信息
     *
     * @param id 服务项主键
     * @return 结果
     */
    @Override
    public int deleteBusServiceItemById(Long id)
    {
        return busServiceItemMapper.deleteBusServiceItemById(id);
    }

    /**
     * 上架功能
     */
    @Override
    public int saleOn(Long id) {
        //  - 参数合理性验证
        if (id == null) {
            throw new RuntimeException("非法参数");
        }
        BusServiceItem busServiceItem = this.selectBusServiceItemById(id);
        if(busServiceItem == null){
            throw new RuntimeException("非法参数");
        }
        // - 必须是下架状态才能实现上架
        if(BusServiceItem.SALESTATUS_ON.equals(busServiceItem.getSaleStatus())){
            throw new RuntimeException("请勿重复上架");
        }
        // - 下架状态 -> 非套餐可以直接上架
        // - 是套餐 -->  只有审批通过才可以进行上架
        if(BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage()) &&
                !BusServiceItem.AUDITSTATUS_APPROVED.equals(busServiceItem.getAuditStatus())){
            throw new RuntimeException("套餐必须审批通过后才可以进行上架操作");
        }
        return busServiceItemMapper.changeSaleStatusById(id,BusServiceItem.SALESTATUS_ON);
    }

    /**
     * 下架功能
     * @param id
     * @return
     */
    @Override
    public int saleOff(Long id) {
        //  - 参数合理性验证
        if (id == null) {
            throw new RuntimeException("非法参数");
        }
        BusServiceItem busServiceItem = this.selectBusServiceItemById(id);
        if(busServiceItem == null){
            throw new RuntimeException("非法参数");
        }
        // - 必须是上架状态才能实现下架
        if(BusServiceItem.SALESTATUS_OFF.equals(busServiceItem.getSaleStatus())){
            throw new RuntimeException("请勿重复下架");
        }

        return busServiceItemMapper.changeSaleStatusById(id,BusServiceItem.SALESTATUS_OFF);
    }

    @Override
    public Map getAuditInfo(Long id) {

        Map map = new HashMap();

        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        map.put("name", busServiceItem.getName());
        map.put("originalPrice", busServiceItem.getOriginalPrice());
        map.put("discountPrice", busServiceItem.getDiscountPrice());

        //查店长，放到map中
        List<SysUser> shopOwnerList =  sysUserService.selectUserbyRoleKey("shopOwner");
        map.put("shopOwenerList", shopOwnerList);
        //查财务，放到map中
        List<SysUser> financeList =  sysUserService.selectUserbyRoleKey("finance");
        map.put("financeList", financeList);
        return map;
    }

    @Override
    public void startAudit(Long serviceItemId, Long shopOwnerId, Long financeId, String info) {
        System.err.println(serviceItemId);
        System.err.println(shopOwnerId);
        System.err.println(financeId);
        System.err.println(info);
        //合理性判断
        if(serviceItemId == null || shopOwnerId == null){
            throw new RuntimeException("非法参数");
        }
        BusServiceItem serviceItem = busServiceItemMapper.selectBusServiceItemById(serviceItemId);
        if(serviceItem == null){
            throw new RuntimeException("非法参数");
        }
        if(serviceItem.getSaleStatus() == BusServiceItem.SALESTATUS_ON){
            throw new RuntimeException("已上架的服务不能发起审核");
        }
        if(serviceItem.getCarPackage() == BusServiceItem.CARPACKAGE_NO){
            throw new RuntimeException("只有套餐可以发起审核");
        }
        if(serviceItem.getAuditStatus() != BusServiceItem.AUDITSTATUS_INIT){
            throw new RuntimeException("只有初始化状态才能发起审核");
        }
        //添加car_package_audit表的记录
        CarPackageAudit audit = new CarPackageAudit();
        audit.setServiceItemId(serviceItem.getId());
        audit.setServiceItemName(serviceItem.getName());
        audit.setServiceItemInfo(serviceItem.getInfo());
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        String userId = SecurityUtils.getUserId().toString();
        audit.setCreatorId(userId);
        audit.setInfo(info);
        audit.setStatus(CarPackageAudit.STATUS_IN_PROGRESS);
        audit.setCreateTime(new Date());
        carPackageAuditMapper.insertCarPackageAudit(audit);
        //到activity中生成流程实例
        BusBpmnInfo bpmnInfo = busBpmnInfoService.getByType(0);
        String processDefinitionKey = bpmnInfo.getProcessDefinitionKey();
        String businessKey = audit.getId().toString();
        Map map = new HashMap();
        map.put("shopOwnerId", shopOwnerId);
        if(financeId != null){
            map.put("financeId", financeId);
        }
        map.put("disCountPrice", audit.getServiceItemPrice().longValue());
        //发起流程实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, map);
        //将activity中生成流程实例的id更新到car_package_audit表中
        String processInstanceId = processInstance.getId();
        audit.setInstanceId(processInstanceId);
        carPackageAuditMapper.updateCarPackageAudit(audit);
        //修改service_item表的状态
        busServiceItemMapper.changeAuditStatus(serviceItemId, BusServiceItem.AUDITSTATUS_AUDITING);
    }
}
